package www.xpu.edu.app;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Activity_login extends AppCompatActivity {
    String user="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //取消标题栏
        ActionBar actionbar=getSupportActionBar();
        if(actionbar!=null)
        {
            actionbar.hide();
        }
        //

        Button login_b1=(Button)findViewById(R.id.login_b1);
        Button login_b2=(Button)findViewById(R.id.login_b2);
        Button login_b3=(Button)findViewById(R.id.login_b3);
        final EditText edit_user=(EditText)findViewById(R.id.edit_user);
        final EditText edit_password=(EditText)findViewById(R.id.edit_password);
        //测试：账号和密码均为admin->跳转到新的Activity
        //反之，提示密码错误，可以点击忘记密码或者注册账户
        login_b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                user=edit_user.getText().toString().trim();
                String password=edit_password.getText().toString().trim();/*
               if(user.equals("admin")&&password.equals("admin")) {
                    Toast.makeText(Activity_login.this, "登录成功，欢迎admin用户！", Toast.LENGTH_SHORT).show();
                    //跳转到宣讲会界面
                    //startActivity(new Intent(Activity_login.this,Activity_talk.class));
                    startActivity(new Intent(Activity_login.this,Activity_findjob.class));
                }
                else
                    Toast.makeText(Activity_login.this,"登录没有成功，请尝试找回密码或者注册新账号。",Toast.LENGTH_SHORT).show();
                // Toast.makeText(Activity_login.this,edit_user.getText().toString().trim()+"##"+edit_password.getText().toString(),Toast.LENGTH_SHORT).show();*/
                //startActivity(new Intent(Activity_login.this,Activity_change.class));
                /*Intent intent=new Intent();
                intent.setClass(Activity_login.this,Activity_change.class);
                intent.putExtra("data",user);
                startActivity(intent);*/
                //输入合法性校验
                if((!user.isEmpty()&&!password.isEmpty()&&user.length()==11)||user.equals("admin"))
                sendReguest(user,password);
                else
                    Toast.makeText(Activity_login.this,"用户名或者密码为空，或者格式错误，请检测之后重新尝试",Toast.LENGTH_SHORT).show();
                //跳转的此页面是选择身份的界面
                //Toast.makeText(Activity_login.this,"测试阶段已经取消密码认证，直接点击登录就可以登录",Toast.LENGTH_SHORT).show();

            }
        });
        login_b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Activity_login.this,Activity_nopsd.class));
                Toast.makeText(Activity_login.this,"点击了忘记密码按钮",Toast.LENGTH_SHORT).show();
            }
        });
        login_b3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到注册页面
                startActivity(new Intent(Activity_login.this,Activity_reg.class));
                Toast.makeText(Activity_login.this,"点击了注册按钮",Toast.LENGTH_SHORT).show();
            }
        });

    }
    public void sendReguest(final String user,final String password){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection=null;
                BufferedReader reader=null;
                //http://localhost:8080/xpu/login?num=19829088780&password=12345678
                try {
                    //188.131.250.4:8080
                    //URL url=new URL("http://192.168.43.188:8080/xpu/login"+"?num="+user+"&password="+password);
                    //URL url=new URL("http://188.131.250.4:8080/xpu/login"+"?num="+user+"&password="+password);
                    URL url=new URL("http://188.131.250.4:8080/xpu/login"+"?num="+user+"&password="+password);
                    connection=(HttpURLConnection)url.openConnection();
                    //connection.setRequestMethod("GET");
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream ips=connection.getInputStream();
                    reader=new BufferedReader(new InputStreamReader(ips));
                    StringBuilder response=new StringBuilder();
                    String line;
                    while((line=reader.readLine())!=null)
                    {
                        response.append(line);
                    }
                    System.out.println(response.toString());
                    System.out.println(response.toString().substring(0,4));
                    showResponse(user,response.toString().substring(0,4));
                    /*user初始信息格式：登录成功18812341234@用户@西安交通大学@光电信息与技术
                    登陆失败@@@
                    登陆成功@@@
                    约定如果什么信息都没填，则跳转到信息选择页；
                    */

                    //必须进行判断，不然会StringIndexOutOfBoundsException错误
                    if(response.toString().substring(0,4).equals("登录成功"))
                    System.out.println(response.toString().substring(15,response.length()));

                    //此模块用于将num字符利用sharedpreferences保存【num值非常重要】
                    SharedPreferences.Editor editor=getSharedPreferences("num",MODE_PRIVATE).edit();

                   /* if(response.substring(0,4).trim().equals("登陆失败"))
                        startActivity(new Intent(Activity_login.this,Activity_login.class));*/
                    String[] split = response.toString().trim().split("@");
                    for (int i = 0; i < split.length; i++) {
                        System.out.print("split["+i+"]="+split[i]);
                    }
                    System.out.println(split.length);
                    System.out.println();

                    if(response.substring(0,4).trim().equals("登录成功")&&((split.length==4)))
                    {
                        editor.putString("num",response.toString().substring(4,15));
                        System.out.println("存储的手机号是"+response.toString().substring(4,15));
                        editor.apply();
                        startActivity(new Intent(Activity_login.this,Activity_findjob.class));
                    }
                    else if(response.substring(0,4).trim().equals("登录成功"))
                    {
                        editor.putString("num",response.toString().substring(4,15));
                        System.out.println("存储的手机号是"+response.toString().substring(4,15));
                        editor.apply();
                        startActivity(new Intent(Activity_login.this,Activity_change.class));}

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void showResponse(final String num,final String response)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(response.substring(0,4).equals("登录成功"))
                {
                    Toast.makeText(Activity_login.this,"登录成功,欢迎"+num+"用户登录",Toast.LENGTH_LONG).show();
                }
                else
                    Toast.makeText(Activity_login.this,"登录失败或账号未审核通过，请尝试重置密码或联系管理员",Toast.LENGTH_LONG).show();
            }
        });
    }
}
